<?php

namespace Pocker\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Request;

class AdminController extends Controller {
	public function indexAction() {
		return $this -> render('PockerAdminBundle:Admin:index.html.twig', array());
	}

	public function loginAction() {
		$request = $this -> getRequest();
		$session = $request -> getSession();
		$response = new Response();

		//Get Info Form login
		$sUsername = "";
		$sPassword = "";
		$sRememberMe = 0;

		foreach ($session->getFlashBag()->get("username", array()) as $row) {
			$sUsername = $row;
		}
		foreach ($session->getFlashBag()->get("password", array()) as $row) {
			$sPassword = $row;
		}
		foreach ($session->getFlashBag()->get("remember_me", array()) as $row) {
			$sRememberMe = $row;
		}

		if ($sUsername == "" && $sPassword == "") {
			if (isset($_COOKIE["cms_cookie_login"])) {
				$aCookieLoginInfo = json_decode($_COOKIE["cms_cookie_login"], true);
				$sUsername = $aCookieLoginInfo["username"];
				$sPassword = $aCookieLoginInfo["password"];
				$sRememberMe = $aCookieLoginInfo["remember_me"];
			}
		}

		//Get Error Login
		$sUsernameErr = "";
		$sPasswordErr = "";
		$sInvalidAccount = "";
		foreach ($session->getFlashBag()->get("err_username", array()) as $row) {
			$sUsernameErr = $row;
		}
		foreach ($session->getFlashBag()->get("err_password", array()) as $row) {
			$sPasswordErr = $row;
		}
		foreach ($session->getFlashBag()->get("err_invalid_account", array()) as $row) {
			$sInvalidAccount = $row;
		}
		$aErr = array("username" => $sUsernameErr, "password" => $sPasswordErr, "invalidaccount" => $sInvalidAccount);
		// get the login error if there is one
		if ($request -> attributes -> has(SecurityContext::AUTHENTICATION_ERROR)) {
			$error = $request -> attributes -> get(SecurityContext::AUTHENTICATION_ERROR);
		} else {
			$error = $session -> get(SecurityContext::AUTHENTICATION_ERROR);
			$session -> remove(SecurityContext::AUTHENTICATION_ERROR);
		}

		return $this -> render('PockerAdminBundle:Admin:login.html.twig', array(
		// last username entered by the user
		'last_username' => $session -> get(SecurityContext::LAST_USERNAME),
		//'username'		=> $sUsername,
		'error' => $aErr, 'sUsername' => $sUsername, 'sPassword' => $sPassword, 'sRememberMe' => $sRememberMe));

	}

}
